package com.example.myapplication.flutter;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.orhanobut.logger.Logger;

import io.flutter.embedding.android.FlutterView;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.plugin.common.BasicMessageChannel;
import io.flutter.plugin.common.StringCodec;

public class AndroidToFlutter extends AppCompatActivity {
    private static FlutterEngine flutterEngine;
    private FlutterView flutterView;
    private static final String CHANNEL = "increment";
    BasicMessageChannel messageChannel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.androidtoflutter);
        if (flutterEngine == null) {
            flutterEngine = new FlutterEngine(this);
            flutterEngine.getDartExecutor().executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());

        }
        flutterView = findViewById(R.id.flutter_view);
        flutterView.attachToFlutterEngine(flutterEngine);

//        messenger参数是消息信使（FlutterView），是消息发送和接受的工具。
//        name参数是channel的名字也是其唯一标识，要和Dart端统一。
//        codec是消息编解码器，也需要和Dart端统一。它的作用就是将消息在发送的时候进行加密，dart端收到消息后在进行解密，传递的都是二进制数据。
        messageChannel = new BasicMessageChannel<>(flutterEngine.getDartExecutor(), CHANNEL, StringCodec.INSTANCE);
        messageChannel.
                setMessageHandler(new BasicMessageChannel.MessageHandler<String>() {
                    @Override
                    public void onMessage(String s, BasicMessageChannel.Reply<String> reply) {
                        //参数message即为Dart发送的数据, reply是用于回复消息的回调函数
                        Logger.d("===onMessage: sss="+s);
                        reply.reply("reply是用于回复消息的回调函数");
                    }
                });

        messageChannel.send("发送数据到flutter");
//        messageChannel.send("发送数据到flutter", new BasicMessageChannel.Reply() {
//            @Override
//            public void reply(@Nullable Object reply) {
//                Logger.d( "===reply: 参数message即为要发生给Dart的数据，callback回调则是用于接收Dart端收到消息后的回复信息");
//            }
//        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        flutterEngine.getLifecycleChannel().appIsResumed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        flutterEngine.getLifecycleChannel().appIsInactive();
    }

    @Override
    protected void onStop() {
        super.onStop();
        flutterEngine.getLifecycleChannel().appIsPaused();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        flutterView.detachFromFlutterEngine();
    }
}
